package com.botu.oauth2.server.config.service;

import com.botu.oauth2.entity.Permission;
import com.botu.oauth2.entity.User;
import com.botu.oauth2.service.IPermissionService;
import com.botu.oauth2.service.IUserService;
import org.assertj.core.util.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * @Author: hanzeyao
 * @Date: 2020/2/14 15:44
 * @Description: 自定义认证与授权
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IPermissionService permissionService;
    @Autowired
    private IUserService userService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        // 查询用户信息
        User user = userService.getUserByUserName(username);
        List<GrantedAuthority> grantedAuthorities = Lists.newArrayList();;
        if(user != null){
            //获取用户授权
            List<Permission> permissionList = permissionService.selectByUserId(user.getId());

            //声明用户授权
            permissionList.forEach(permission -> {
                if(permission!=null && !StringUtils.isEmpty(permission.getEnname())){
                    GrantedAuthority grantedAuthority = new SimpleGrantedAuthority(permission.getEnname());
                    grantedAuthorities.add(grantedAuthority);
                }
            });
        }
        //由spring security框架完成认证
        return new org.springframework.security.core.userdetails.User(user.getUsername(),user.getPassword(),grantedAuthorities);
    }

}
